package cn.xuqiudong.backend.base.helper;

import cn.dev33.satoken.stp.StpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 描述:
 * 用户信息等 从sa-token中获取
 *
 * @author Vic.xu
 * @since 2025-02-07 17:23
 */
public class SaSessionHelper {

    public static final String USER_KEY = "_sa_user";

    public static final Integer DEFAULT_USER_ID = -1;

    private static final Logger LOGGER = LoggerFactory.getLogger(SaSessionHelper.class);

    /**
     * 存储与用户
     */
    public static void storeUser(SessionUserInfo user) {
        try {
            StpUtil.getSession().set(USER_KEY, user);
        } catch (Exception e) {
            LOGGER.error("存储用户信息失败", e);
        }
    }

    /**
     * 获取用户
     */
    public static SessionUserInfo getUser() {
        try {
            return (SessionUserInfo) StpUtil.getSession().get(USER_KEY);
        } catch (Exception e) {
            LOGGER.error("获取用户信息失败", e);
            return null;
        }
    }

    /**
     * 获取用户的角色
     */
    public static List<String> getRoles(){
        try {
            SessionUserInfo user = getUser();
            if (user != null) {
                return user.getRoles();
            }
        } catch (Exception e) {
            LOGGER.error("获取用户角色失败", e);
            return null;
        }
        return null;
    }

    /**
     * 获取用户的权限
     */
    public static List<String> getPermissions(){
        try {
            SessionUserInfo user = getUser();
            if (user != null) {
                return user.getPermissions();
            }
        } catch (Exception e) {
            LOGGER.error("获取用户权限失败", e);
            return null;
        }
        return null;
    }

    /**
     * 获取用户ID
     */
    public static Integer getUserIdWithDefault() {
        try {
            return StpUtil.getLoginIdAsInt();
        } catch (Exception e) {
            LOGGER.error("获取用户ID失败", e);
            return DEFAULT_USER_ID;
        }
    }
}
